//
//  HorizontalCalendarView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/8.
//


import SwiftUI

struct HorizontalCalendarView: View {
    let days: [Int]
    @Binding var selectedDay: Int
    let currentDate: Date
    
    var body: some View {
        GeometryReader { geometry in
            ScrollViewReader { proxy in
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(spacing: 15) {
                        ForEach(days, id: \.self) { day in
                            CalendarDayView(
                                day: day,
                                isSelected: day == selectedDay,
                                isToday: isToday(day: day)
                            )
                            .id(day)
                            .onTapGesture { selectDay(day) }
                        }
                    }
                    .padding(.horizontal, geometry.size.width/2 - 25)
                }
                .onAppear { scrollToSelectedDay(proxy) }
                .onChange(of: selectedDay) { _ in
                    scrollToSelectedDay(proxy)
                }
            }
        }
        .frame(height: 60)
    }
    
    private func scrollToSelectedDay(_ proxy: ScrollViewProxy) {
        withAnimation {
            proxy.scrollTo(selectedDay, anchor: .center)
        }
    }
    
    private func selectDay(_ day: Int) {
        selectedDay = day
    }
    
    private func isToday(day: Int) -> Bool {
        Calendar.current.component(.day, from: currentDate) == day
    }
}

struct CalendarDayView: View {
    let day: Int
    let isSelected: Bool
    let isToday: Bool
    
    var body: some View {
        if isSelected {
            Text("\(TimestampHelper.getMonthName())月\(day)日")
                .font(.system(size: 16))
                .frame(width: 82, height: 30)
                .foregroundColor(Color(hex: "#0A0A0A"))
                .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")], type: .linear(start: .leading, end: .trailing), cornerRadius: 15.0)
        }else {
            Text("\(day)")
                .font(.system(size: 16, weight: .medium))
                .frame(width: 54, height: 30)
                .background(.clear)
                .foregroundColor(.white)
        }
    }
    
    private var background: some View {
        Group {
            if isSelected {
                Color.blue
            } else if isToday {
                Color.blue.opacity(0.3)
            } else {
                Color.clear
            }
        }
    }
    
    private var foregroundColor: Color {
        isSelected ? Color(hex: "#0A0A0A") : .white
    }
}

